#include "cJSON_static_mem.h"

static uint8_t *pool = CJSON_STATIC_POOL;
static size_t offset = 0;
static size_t watermark = 0; // 历史峰值
//static bool in_use = false;  // 简单串行保护

/* ---------- 内部对齐 ---------- */
static size_t align4(size_t x) { return (x + 3u) & ~3u; }

/* ---------- 分配 ---------- */
static void *sm_malloc(size_t sz)
{
  sz = align4(sz);
  if (offset + sz > CJSON_STATIC_POOL_SIZE)
    return NULL;
  void *ret = &pool[offset];
  offset += sz;
  if (offset > watermark)
    watermark = offset;
  return ret;
}

/* ---------- 空钩子 ---------- */
static void sm_free(void *p) { (void)p; }

/* ---------- 池初始化 ---------- */
void cJSON_StaticMem_Init(void)
{
  offset = 0;
//  in_use = true;
  static cJSON_Hooks hooks = {sm_malloc, sm_free};
  cJSON_InitHooks(&hooks);
}

/* ---------- 回滚到标记 ---------- */
size_t cJSON_StaticMem_TakeMark(void) { return offset; }

void cJSON_StaticMem_Rollback(size_t mark)
{
  offset = mark;
}

/* ---------- 统计 ---------- */
size_t cJSON_StaticMem_Watermark(void) { return watermark; }
size_t cJSON_StaticMem_Left(void) { return CJSON_STATIC_POOL_SIZE - offset; }
void cJSON_StaticMem_Reset(void) { offset = 0; }

/* ---------- 线程安全封装（可选） ---------- */
#ifdef CJSON_STATIC_MUTEX
#include "cmsis_os.h" // 或者 pthread.h
static osMutexId_t mux;
void cJSON_StaticMem_Lock(void) { osMutexAcquire(mux, osWaitForever); }
void cJSON_StaticMem_Unlock(void) { osMutexRelease(mux); }
#endif


